package pl.darbat.photogallery.html;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;

import pl.darbat.photogallery.Debug;
import android.app.Activity;
import android.content.Context;
import android.util.Log;

public class HtmlParser extends Thread {

	private static final String TAG = "HtmlParser";
	private HtmlCleaner mPageParser;
	private CleanerProperties mProps;
	
	private HtmlParserListener mHtmlParserListener;
	private InputStream mInputStream;
	private boolean mIsCanceled = false;
	
	public HtmlParser() {
		mPageParser = new HtmlCleaner();
		mProps = mPageParser.getProperties();
		mProps.setAllowHtmlInsideAttributes(true);
		mProps.setAllowMultiWordAttributes(true);
		mProps.setRecognizeUnicodeChars(true);
		mProps.setOmitComments(true);
	}

	public void cancel(){
		mIsCanceled = true;
	}
	
	private void parsePage(InputStream is) {
		mIsCanceled = false;
		if(mHtmlParserListener != null){
			final List<Map<String, String>> mList = new ArrayList<Map<String, String>>();

			try {
				if(mIsCanceled) return;
				TagNode node = mPageParser.clean(new InputStreamReader(is));

				// XPath:
				// Select out of all 'div' elements with attribute 'class' == 'inside'
				//String xPathExpression = "//div[@class='inside']";
				String xPathExpression = "//div[@class='photo_wszystkie']/div[@class='inside']/a";
				try {
					if(mIsCanceled) return;
					Object[] downloadNodes = node.evaluateXPath(xPathExpression);

					// Iterate through the nodes selected by the XPath statement...
					for (Object aTagObj : downloadNodes) {
						if(mIsCanceled) return;
						try {
							if (aTagObj != null) {
								Log.v(TAG, "atag: " + aTagObj.toString());
								TagNode aTag = (TagNode) aTagObj;
								HashMap<String, String> element = new HashMap<String, String>();
								String href = aTag.getAttributeByName("href");
								String title = aTag.getAttributeByName("title");
								String src = null;
								TagNode imgTag = (TagNode) aTag.getChildren().get(0);
								if (imgTag != null) {
									src = imgTag.getAttributeByName("src");
									String full = src.replace("mini_new2", "zdjecia_new2");
									element.put("miniImage", src);
									element.put("fullImage", full);
								}
								if(title == null) continue;
								element.put("link", href);
								element.put("description", title);
								if(Debug.HTMLPARSER) Log.v(TAG, "href: " + href + "\nsrc: " + src + "\ntitle: " + title);
								mList.add(element);
							}
						} catch (Exception e) {
							if (Debug.HTMLPARSER) Log.e(TAG,"", e);
						}
					}
				} catch (XPatherException e) {
					if (Debug.HTMLPARSER) Log.e(TAG,"", e);
				}
				is.close();
			} catch (IOException e) {
				if (Debug.HTMLPARSER) Log.e(TAG,"", e);
			}
			mHtmlParserListener.onParseResult(mList);
		}
	}

	public void setHtmlParserListener(HtmlParserListener htmlParserListener) {
		mHtmlParserListener = htmlParserListener;
	}

	public void asyncParsePage(InputStream is){
		mIsCanceled = false;
		if(is != null){
			if(mHtmlParserListener != null ){
				mInputStream = is;
				this.start();
			} else {
				throw new IllegalStateException("HtmlParserListener is not set.");
			}
		} else {
			throw new IllegalArgumentException("HtmlParserListener is not set.");
		}
	}
	
	@Override
	public void run() {
		parsePage(mInputStream);
	}

}
